<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams">
        <el-row>
          <el-col :span="3">
            <el-form-item prop="keywords" label="关键字:">
              <el-input
                v-model="queryParams.keywords"
                placeholder="关键字"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="3">
            <el-form-item prop="createTimes" label="创建时间:">
              <el-date-picker
                v-model="queryParams.createTimes"
                type="daterange"
                unlink-panels
                value-format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :shortcuts="shortcuts"
                :size="size"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
        </el-row>
        <el-row justify="end">
          <el-col :span="2">
            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
      >
        <el-table-column label="简历名称" prop="resumeName" min-width="100" />
        <el-table-column label="创建时间" prop="createTime" width="200" />
        <el-table-column label="修改时间" prop="updateTime" width="200" />
        <el-table-column fixed="right" label="操作" min-width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              icon="view"
              @click="handleViewDialog(scope.row.id)"
            >
              查看
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 岗位信息 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="900px"
      @close="handleCloseDialog"
    >
      <el-form
        v-if="dialog.visible"
        ref="formRef"
        v-loading="dialogLoad"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="简历名称" prop="resumeName">
              <el-input v-model="formData.resumeName" placeholder="简历名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="教育背景" prop="eduBackground">
              <QuillEditor ref="eduEditor" v-model="formData.eduBackground" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="技能" prop="skill">
              <QuillEditor ref="skillEditor" v-model="formData.skill" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="实践经历" prop="practicalExperience">
              <QuillEditor ref="experEditor" v-model="formData.practicalExperience" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="自我评价" prop="selfEvaluation">
              <QuillEditor ref="selfEditor" v-model="formData.selfEvaluation" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件上传" prop="fileId">
              <FillUpload
                v-if="fileLoad"
                v-model="fileList"
                :limit="1"
                :accept="accept"
              ></FillUpload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCloseDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="viewDialog.visible"
      :title="viewDialog.title"
      width="900px"
      @close="handleCloseView"
    >
      <el-form
        v-if="viewDialog.visible"
        ref="formRef"
        v-loading="dialogLoad"
        :model="formData"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="简历名称" prop="resumeName">
              {{ formData.resumeName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="教育背景" prop="eduBackground">
              <QuillViewer v-model="formData.eduBackground" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="技能" prop="skill">
              <QuillViewer v-model="formData.skill" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="实践经历" prop="practicalExperience">
              <QuillViewer v-model="formData.practicalExperience" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="自我评价" prop="selfEvaluation">
              <QuillViewer v-model="formData.selfEvaluation" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.fileId">
          <el-col :span="24">
            <el-form-item label="附件" prop="fileId">
              <div class="el-upload-list__item-info">
                <a class="el-upload-list__item-name" @click="handleDownload(file)">
                  <el-icon><Document /></el-icon>
                  <span class="el-upload-list__item-file-name">{{ file?.fileName }}</span>
                </a>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseView">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import ResumeApi, { Resume, ResumePageQuery, ResumeVo } from "@/api/resume/resume.api";
import dayjs from "dayjs";
import QuillEditor from "@/components/QuillEditor/index.vue";
import QuillViewer from "@/components/QuillEditor/viewer.vue";
import FillUpload from "@/components/Upload/FileUpload.vue";
import FileAPI, { FileInfo } from "@/api/file.api";

const size = ref<"default" | "large" | "small">("default");

const fileList = ref();

const file = ref<FileInfo>();

const accept = "application/pdf,application/msword";

/**
 * 日期选择范围
 */
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

defineOptions({
  name: "Resume",
  inheritAttrs: false,
});

const queryFormRef = ref();
const formRef = ref();
const dataTableRef = ref();
const loading = ref(false);
const total = ref(0);

const queryParams = reactive<ResumePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 表格数据
const dataList = ref<ResumeVo[]>();

const eduEditor = ref();
const skillEditor = ref();
const experEditor = ref();
const selfEditor = ref();
const fileLoad = ref(false);

// 查询
function handleQuery() {
  loading.value = true;
  if (queryParams.createTimes) {
    queryParams.createTimeStart = queryParams.createTimes[0];
    queryParams.createTimeEnd = queryParams.createTimes[1];
  } else {
    queryParams.createTimeStart = undefined;
    queryParams.createTimeEnd = undefined;
  }
  ResumeApi.getPage(queryParams)
    .then((data) => {
      dataList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.createTimes = lastWeek();
  handleQuery();
}

// 新增弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 详情弹窗
const viewDialog = reactive({
  title: "",
  visible: false,
});

const dialogLoad = ref(false);

// 表单
const formData = reactive<Resume>({});

// 打开弹窗
function handleOpenDialog(id?: string) {
  dialog.visible = true;
  fileLoad.value = true;
  if (id) {
    dialog.title = "修改简历信息";
    dialogLoad.value = true;
    ResumeApi.getFormData(id).then((data) => {
      dialogLoad.value = false;
      if (data.fileId) {
        fileLoad.value = false;
        FileAPI.getById(data.fileId).then((data) => {
          fileList.value = [{ ...data, name: data.fileName }];
          fileLoad.value = true;
        });
      }
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增简历";
  }
}

const rules = reactive({
  resumeName: [{ required: true, message: "请输入简历名称", trigger: "blur" }],
  eduBackground: [{ required: true, message: "请输入教育背景", trigger: "blur" }],
  skill: [{ required: true, message: "请输入技能", trigger: "blur" }],
  practicalExperience: [{ required: true, message: "请输入实践经历", trigger: "blur" }],
  selfEvaluation: [{ required: true, message: "请输入自我评价", trigger: "blur" }],
});

// 提交表单
function handleSubmit() {
  formRef.value.validate((valid: any) => {
    if (valid) {
      dialogLoad.value = true;
      const id = formData.id;
      if (id) {
        const {
          revision,
          createTime,
          createUserId,
          createUserName,
          updateTime,
          updateUserId,
          updateUserName,
          ...submitData
        } = formData;
        if (fileList.value) {
          submitData.fileId = fileList.value[0].id;
        }
        ResumeApi.update(id, submitData)
          .then(() => {
            ElMessage.success("修改成功");
          })
          .finally(() => (dialogLoad.value = false));
      } else {
        ResumeApi.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (dialogLoad.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  fileLoad.value = false;

  resetFormData();
}

function resetFormData() {
  if (formRef.value) {
    formRef.value.resetFields();
    formRef.value.clearValidate();
  }
  file.value = undefined;
  fileList.value = undefined;
  formData.id = undefined;
  formData.eduBackground = undefined;
  formData.skill = undefined;
  formData.practicalExperience = undefined;
  formData.selfEvaluation = undefined;
  formData.revision = undefined;
  formData.createTime = undefined;
  formData.createUserId = undefined;
  formData.createUserName = undefined;
  formData.updateTime = undefined;
  formData.updateUserId = undefined;
  formData.updateUserName = undefined;
}

function handleViewDialog(id: string) {
  viewDialog.visible = true;
  viewDialog.title = "简历信息";
  dialogLoad.value = true;
  ResumeApi.getFormData(id).then((data) => {
    if (data.fileId) {
      FileAPI.getById(data.fileId).then((data) => {
        file.value = data;
      });
    }
    dialogLoad.value = false;
    Object.assign(formData, data);
  });
}

function handleDownload(file?: FileInfo) {
  if (file?.id) {
    const { id, fileName } = file;
    FileAPI.download(id, fileName);
  }
}

function handleCloseView() {
  viewDialog.visible = false;
  resetFormData();
}

// 删除
function handleDelete(id: string) {
  ElMessageBox.confirm("当前操作将永久删除该简历，是否继续?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ResumeApi.deleteById(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      // ElMessage.info("已取消删除");
    }
  );
}

function lastWeek() {
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
  return [dayjs(start).format("YYYY-MM-DD"), dayjs(end).format("YYYY-MM-DD")];
}

onMounted(() => {
  queryParams.createTimes = lastWeek();
  handleQuery();
});
</script>

<style lang="scss" scoped>
.viewer {
  .ql-toolbar.ql-snow {
    display: none !important;
  }
}
</style>
